
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.EventListener;


public class DrawingCanvas extends JComponent {

  protected Image imageBuffer;
  protected Graphics imageBufferGraphics;
  protected Tool currentTool;
  protected int canvasWidth;
  protected int canvasHeight;
  protected Color penColor = Color.black;
  public MultiDraw2 md;
  
  /* constructor */
  public DrawingCanvas(MultiDraw2 m) {
    setBackground(Color.white);
    this.md = m;
  }

  protected void addDrawingCanvasListener(EventListener listener) {
    addMouseListener((MouseListener) listener);
    addMouseMotionListener((MouseMotionListener) listener);
  }

  public void update(Graphics g){
     paint(g);
  }
  public void paint(Graphics g) {
     g.drawImage(imageBuffer,0, 0, this);
  }
  
  public void drawLineSegment(Point p1, Point p2) {
   imageBufferGraphics.drawLine(p1.x,p1.y,
                	       p2.x, p2.y);
   repaint();
  }
  public void setBounds(int x, int y, int width, int height) {
	  if(width <= 0)
		  width = - width;
	  if(height <= 0)
		  height = -height;
    Image newimageBuffer = createImage(width, height);
    imageBufferGraphics = newimageBuffer.getGraphics();
    if (imageBuffer != null) {
      imageBufferGraphics.drawImage(imageBuffer, 0, 0 ,this);
    }
    imageBuffer = newimageBuffer;
    super.setBounds(x, y, width, height);
    repaint();
    if(currentTool !=  null){
    	Graphics iBGraphics = getImageBufferGraphics();
    	iBGraphics.setFont(new Font("Serif", Font.BOLD, 24));
    	currentTool.paintObjects(1);
    }
    
    
    canvasWidth = width;
    canvasHeight = height;
    setPenColor(penColor);
  }
 	
  public void setPenColor(Color c) {
	    penColor = c;
	    imageBufferGraphics.setColor(penColor);
	  }

	  public void clearCanvas() {
	   imageBufferGraphics.setColor(Color.white);
	   imageBufferGraphics.fillRect(0, 0, canvasWidth, canvasHeight);
	   imageBufferGraphics.setColor(penColor);
	  }
	  public Graphics getImageBufferGraphics() {
		    return imageBufferGraphics; 
		  }

		  public Tool getCurrentTool() {
		    return currentTool;
		  }

		  public void setCurrentTool(Tool tool) {
			  currentTool = tool;
		  }
}
